#include<stdio.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdlib.h>
#include<assert.h>
void task_1(){
	printf("execute test_1 ....\n");
	sleep(2);
}

void task_2(){
	printf("execute test_2 ....\n");
	sleep(2);
}

void task_3(){
	printf("execute test_3 ....\n");
	sleep(2); 
}

void task_4(){
	printf("execute test_4 ....\n");
	sleep(2);
}
void (* task[10])() = {task_1,task_2,task_3,task_4};   
int task_i = 0;

int main(){
	pid_t id = fork();
	assert(id >= 0);
	if(!id){
		for(int i = 0;i<5;i++){
			printf("I am a child my pid:%d my ppid:%d\n",getpid(),getppid());
			sleep(2);
		}
		exit(1);
	}
	sleep(5);
	while(1){ 
		int status = 0;
		pid_t ret = waitpid(id,&status,WNOHANG);
		if(ret > 0){
			if(WIFEXITED(status)){
		    	//printf("child wait success!!! pid:%d signal:%d status:%d\n",ret,(status&0x7f),(status>>8&0xff));
				printf("status:%d\n",WEXITSTATUS(status));		
			}
			else
				printf("child error!!\n");
			break;
		}	
		else if( ret< 0){  //wait/waitpid error return -1
			printf("pid error!!\n");
			break;
		}
		else{  //ret == 0
			if(task[task_i]){
				 task[task_i]();
				task_i++;
			}
			else
				printf("task queue execute finish !");
					
		}
			
	}
	printf("execute until task:%d\n",task_i);
	while(task[task_i]){
		task[task_i]();
		task_i++;
	}
	sleep(5);
	exit(0);
	return 0;
}

